package com.chenyi.leetcode.editor.cn;

/**
 * [28]实现 strStr()
 *
 * @author by chenyi
 * @className ImplementStrstr
 * @date 2022-06-20 22:12:27d
 */
public class ImplementStrstr {
    public static void main(String[] args) {
        //"mississippi"
        //"issipi"
        Solution solution = new ImplementStrstr().new Solution();
        System.out.println(solution.strStr("mississippi", "issip"));
    }

    @SuppressWarnings("AlibabaCommentsMustBeJavadocFormat")
            //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        /**
         * 暴力匹配算法
         * @param haystack
         * @param needle
         * @return
         */
        public int strStr(String haystack, String needle) {
            if ("".equals(needle)) {
                return 0;
            }
            if (needle.length() > haystack.length()) {
                return -1;
            }
            char[] chars = haystack.toCharArray();
            char[] chars1 = needle.toCharArray();
            int i = 0;
            int j = 0;
            while (i < haystack.length() && j < needle.length()) {
                if (chars[i] == chars1[j]) {
                    i++;
                    j++;
                } else {
                    i = i - (j - 1);
                    j = 0;
                }
            }
            return j == needle.length() ? i - j : -1;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
